// Editor: myBigPro9/src/views/teacher/DocumentSolver.vue
// Action: Update UI layout and result panel styling
<template>
  <div class="document-solver-wrapper">
    <div class="animated-background">
      <div class="floating-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
        <div class="shape shape-5"></div>
      </div>
    </div>

    <div class="container">
      <div class="header-section">
        <div class="header-icon">
          <el-icon><DocumentChecked /></el-icon>
        </div>
        <div class="header-title-text">
          <h1 class="main-title">AI 智能文档解析</h1>
          <p class="subtitle">让人工智能为您深度解析文档中的每一道题目</p>
        </div>
      </div>

      <div v-if="!analysisResults.length" class="upload-container">
        <el-card class="upload-card" shadow="hover">
          <div class="upload-content">
            <el-upload
              ref="uploadRef"
              drag
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              :limit="1"
              accept=".doc,.docx"
              class="enhanced-uploader"
            >
              <div class="upload-icon-container">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-ripple"></div>
              </div>
              <div class="upload-text">
                <h3>拖拽文档至此处</h3>
                <p>或点击选择 Word 文档</p>
              </div>
              <div class="upload-features">
                <div class="feature-item">
                  <el-icon><Check /></el-icon>
                  <span>支持 .doc / .docx 格式</span>
                </div>
                <div class="feature-item">
                  <el-icon><Check /></el-icon>
                  <span>智能识别题目结构</span>
                </div>
                <div class="feature-item">
                  <el-icon><Check /></el-icon>
                  <span>深度解析每道题目</span>
                </div>
              </div>
            </el-upload>
            
            <div v-if="documentFile" class="file-info">
              <div class="file-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="file-details">
                <p class="file-name">{{ documentFile.name }}</p>
                <p class="file-size">{{ formatFileSize(documentFile.size) }}</p>
              </div>
              <div class="file-status">
                <el-icon class="status-icon"><CircleCheck /></el-icon>
              </div>
            </div>

            <div class="action-section">
              <el-button 
                type="primary" 
                size="large"
                @click="handleAnalyze" 
                :loading="isLoading" 
                :disabled="!documentFile"
                class="analyze-button"
              >
                <el-icon v-if="!isLoading"><DataLine /></el-icon>
                <span>{{ isLoading ? '正在全力解析中...' : '开始智能解析' }}</span>
              </el-button>
            </div>
          </div>
        </el-card>

        <div v-if="isLoading" class="loading-overlay">
          <div class="loading-content">
            <div class="loading-spinner">
              <div class="spinner-ring"></div>
              <div class="spinner-ring"></div>
              <div class="spinner-ring"></div>
            </div>
            <h3>AI 正在深度解析您的文档</h3>
            <p>请稍候，这可能需要几分钟时间...</p>
            <div class="loading-steps">
              <div class="step active">
                <div class="step-icon">1</div>
                <span>读取文档内容</span>
              </div>
              <div class="step active">
                <div class="step-icon">2</div>
                <span>识别题目结构</span>
              </div>
              <div class="step loading">
                <div class="step-icon">3</div>
                <span>AI 智能解析</span>
              </div>
              <div class="step">
                <div class="step-icon">4</div>
                <span>生成解答报告</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="results-container">
        <div class="results-header">
          <el-button 
            @click="reset" 
            type="text" 
            class="back-button"
          >
            <el-icon><ArrowLeft /></el-icon>
            返回上传
          </el-button>
          <div class="results-info">
            <h2>解析结果</h2>
            <p>成功解析出 {{ analysisResults.length }} 道题目</p>
          </div>
        </div>

        <div class="results-grid">
          <div 
            v-for="(item, index) in analysisResults" 
            :key="index"
            class="result-card"
            :class="{ 'active': activeResult === index }"
            @click="activeResult = index"
          >
            <div class="result-card-header">
              <div class="question-number">{{ index + 1 }}</div>
              <div class="question-preview">
                <h4>{{ item.originalQuestion.substring(0, 50) }}...</h4>
                <div class="question-meta">
                  <span class="meta-item">
                    <el-icon><Clock /></el-icon>
                    刚刚解析
                  </span>
                  <span class="meta-item">
                    <el-icon><ChatDotSquare /></el-icon>
                    详细解答
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="activeResult !== null" class="solution-panel">
          <el-card class="solution-card" shadow="hover">
            <template #header>
              <div class="solution-header">
                <h3>题目 {{ activeResult + 1 }} 详细解答</h3>
                <div>
                  <el-button 
                    type="primary" 
                    plain
                    :icon="CopyDocument" 
                    @click.stop="copySolution(analysisResults[activeResult].detailedSolution)"
                  >
                    复制解答
                  </el-button>
                  <el-button type="text" @click.stop="activeResult = null" style="margin-left: 12px;">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            
            <div class="solution-content">
              <div class="question-section">
                <h4>
                  <el-icon><QuestionFilled /></el-icon>
                  原始题目
                </h4>
                <div class="question-text">
                  {{ analysisResults[activeResult].originalQuestion }}
                </div>
              </div>

              <el-divider />

              <div class="answer-section">
                <h4>
                  <el-icon><MagicStick /></el-icon>
                  AI 详细解答
                </h4>
                <div class="solution-text-container">
                  <div class="solution-text" v-html="formatMarkdown(analysisResults[activeResult].detailedSolution)"></div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  UploadFilled, 
  DataLine, 
  DocumentChecked, 
  Check, 
  Document, 
  CircleCheck,
  ArrowLeft,
  Clock,
  ChatDotSquare,
  Close,
  QuestionFilled,
  MagicStick,
  CopyDocument
} from '@element-plus/icons-vue';
import documentAnalysisService from '../../services/documentAnalysisService';
import MarkdownIt from 'markdown-it';

const uploadRef = ref();
const documentFile = ref(null);
const isLoading = ref(false);
const analysisResults = ref([]);
const activeResult = ref(null);

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

const formatMarkdown = (text) => md.render(text || '');

const copySolution = async (text) => {
  if (!navigator.clipboard) {
    ElMessage.error('您的浏览器不支持复制功能');
    return;
  }
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('解答已成功复制到剪贴板！');
  } catch (err) {
    ElMessage.error('复制失败: ' + err.message);
  }
};

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const handleFileChange = (file) => {
  const isDoc = file.name.endsWith('.doc') || file.name.endsWith('.docx');
  if (!isDoc) {
    ElMessage.error('请上传 Word 文档格式文件！');
    uploadRef.value.clearFiles();
    return;
  }
  documentFile.value = file;
};

const handleAnalyze = async () => {
    if (!documentFile.value) {
        ElMessage.warning('请先选择一个Word文档');
        return;
    }
    isLoading.value = true;
    try {
        const data = await documentAnalysisService.solveFromDocument(documentFile.value.raw);
        if (data.error) { throw new Error(data.error); }
        analysisResults.value = data;
        ElMessage.success(`成功解析出 ${data.length} 道题目！`);
    } catch (error) {
        ElMessage.error('解析失败: ' + error.message);
    } finally {
        isLoading.value = false;
    }
};

const reset = () => {
    documentFile.value = null;
    analysisResults.value = [];
    activeResult.value = null;
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
};
</script>

<style scoped>
.document-solver-wrapper {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

/* 背景动画 */
.animated-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.floating-shapes {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.shape {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}
.shape-1 { width: 80px; height: 80px; top: 10%; left: 10%; animation-delay: 0s; }
.shape-2 { width: 60px; height: 60px; top: 20%; right: 20%; animation-delay: 2s; }
.shape-3 { width: 100px; height: 100px; bottom: 20%; left: 20%; animation-delay: 4s; }
.shape-4 { width: 40px; height: 40px; bottom: 30%; right: 10%; animation-delay: 1s; }
.shape-5 { width: 70px; height: 70px; top: 50%; left: 50%; animation-delay: 3s; }

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

/* 标题区域 (已修改) */
.header-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40px; /* 减少了 margin-bottom */
  color: white;
}

.header-icon {
  font-size: 56px; /* 稍微缩小图标 */
  margin-right: 24px;
  animation: pulse 2s infinite;
  flex-shrink: 0;
}

.header-title-text {
  text-align: left; /* 文本左对齐 */
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.main-title {
  font-size: 42px; /* 稍微缩小标题 */
  font-weight: 700;
  margin: 0 0 8px 0; /* 调整了 margin */
  background: linear-gradient(45deg, #fff, #e0e7ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

/* 上传区域 */
.upload-container { position: relative; }
.upload-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 24px;
  border: none;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
.upload-card:hover { transform: translateY(-5px); box-shadow: 0 30px 60px rgba(0, 0, 0, 0.15); }
.upload-content { padding: 40px; }
.enhanced-uploader { width: 100%; }
.enhanced-uploader :deep(.el-upload) {
  width: 100%;
  border: 2px dashed #d1d5db;
  border-radius: 16px;
  padding: 60px 40px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  position: relative;
  overflow: hidden;
}
.enhanced-uploader :deep(.el-upload:hover) { border-color: #667eea; background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); }
.upload-icon-container { position: relative; display: inline-block; margin-bottom: 24px; }
.upload-icon { font-size: 64px; color: #667eea; position: relative; z-index: 2; }
.upload-ripple { position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; border: 2px solid #667eea; border-radius: 50%; transform: translate(-50%, -50%); animation: ripple 2s infinite; opacity: 0.6; }

@keyframes ripple {
  0% { transform: translate(-50%, -50%) scale(0.5); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(1.5); opacity: 0; }
}

.upload-text h3 { font-size: 24px; margin: 0 0 8px 0; color: #374151; }
.upload-text p { font-size: 16px; color: #6b7280; margin: 0; }
.upload-features { display: flex; justify-content: center; gap: 32px; margin-top: 32px; }
.feature-item { display: flex; align-items: center; gap: 8px; color: #059669; font-size: 14px; font-weight: 500; }
.feature-item .el-icon { font-size: 16px; }

/* 文件信息 */
.file-info { display: flex; align-items: center; gap: 16px; margin-top: 24px; padding: 16px; background: #f0f9ff; border-radius: 12px; border: 1px solid #bae6fd; }
.file-icon { font-size: 32px; color: #0284c7; }
.file-details { flex: 1; }
.file-name { font-weight: 600; color: #374151; margin: 0 0 4px 0; }
.file-size { color: #6b7280; font-size: 14px; margin: 0; }
.status-icon { font-size: 24px; color: #059669; }

/* 操作按钮 */
.action-section { text-align: center; margin-top: 32px; }
.analyze-button { font-size: 18px; padding: 16px 48px; border-radius: 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4); transition: all 0.3s ease; }
.analyze-button:hover { transform: translateY(-2px); box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6); }
.analyze-button:disabled { opacity: 0.6; cursor: not-allowed; }

/* 加载状态 */
.loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.loading-content { background: white; padding: 48px; border-radius: 24px; text-align: center; max-width: 500px; width: 90%; }
.loading-spinner { position: relative; width: 80px; height: 80px; margin: 0 auto 32px; }
.spinner-ring { position: absolute; width: 100%; height: 100%; border: 4px solid transparent; border-top: 4px solid #667eea; border-radius: 50%; animation: spin 1s linear infinite; }
.spinner-ring:nth-child(2) { width: 60px; height: 60px; top: 10px; left: 10px; border-top-color: #764ba2; animation-delay: -0.3s; }
.spinner-ring:nth-child(3) { width: 40px; height: 40px; top: 20px; left: 20px; border-top-color: #667eea; animation-delay: -0.6s; }

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-content h3 { font-size: 24px; margin: 0 0 12px 0; color: #374151; }
.loading-content p { color: #6b7280; margin: 0 0 32px 0; }
.loading-steps { display: flex; justify-content: space-between; gap: 16px; }
.step { display: flex; flex-direction: column; align-items: center; gap: 8px; flex: 1; }
.step-icon { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; color: white; background: #d1d5db; transition: all 0.3s ease; }
.step.active .step-icon { background: #059669; }
.step.loading .step-icon { background: #667eea; animation: pulse 1s infinite; }
.step span { font-size: 12px; color: #6b7280; text-align: center; }

/* 结果区域 */
.results-container { color: white; }
.results-header { display: flex; align-items: center; gap: 24px; margin-bottom: 32px; }
.back-button { color: white; font-size: 16px; padding: 12px 24px; border-radius: 8px; background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.2); transition: all 0.3s ease; }
.back-button:hover { background: rgba(255, 255, 255, 0.2); transform: translateX(-4px); }
.results-info h2 { font-size: 32px; margin: 0 0 8px 0; }
.results-info p { opacity: 0.8; margin: 0; }
.results-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 24px; margin-bottom: 32px; }
.result-card { background: rgba(255, 255, 255, 0.95); border-radius: 16px; padding: 24px; cursor: pointer; transition: all 0.3s ease; border: 2px solid transparent; backdrop-filter: blur(10px); }
.result-card:hover { transform: translateY(-4px); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1); }
.result-card.active { border-color: #667eea; box-shadow: 0 20px 40px rgba(102, 126, 234, 0.2); }
.result-card-header { display: flex; align-items: flex-start; gap: 16px; }
.question-number { width: 48px; height: 48px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px; flex-shrink: 0; }
.question-preview { flex: 1; min-width: 0; }
.question-preview h4 { margin: 0 0 12px 0; color: #374151; font-size: 16px; line-height: 1.4; }
.question-meta { display: flex; gap: 16px; }
.meta-item { display: flex; align-items: center; gap: 4px; color: #6b7280; font-size: 12px; }

/* 解答面板 (样式已优化) */
.solution-panel { margin-top: 32px; animation: slideUp 0.3s ease; }

@keyframes slideUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.solution-card {
  background: #ffffff; /* 使用纯白背景以提高对比度 */
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid #e5e7eb; /* 添加一个细边框 */
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
}

.solution-header { display: flex; align-items: center; justify-content: space-between; }
.solution-header h3 { margin: 0; color: #111827; font-size: 20px; } /* 标题颜色加深 */

.solution-content { padding: 8px 24px 24px 24px; } /* 调整内边距 */

.question-section, .answer-section { margin-bottom: 16px; }
.question-section h4, .answer-section h4 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 0 16px 0;
  color: #1f2937; /* 标题颜色加深 */
  font-size: 18px;
  font-weight: 600; /* 标题加粗 */
}

.question-text {
  background: #f8fafc; /* 使用更柔和的背景色 */
  padding: 20px;
  border-radius: 12px;
  border-left: 5px solid #667eea;
  line-height: 1.7; /* 增加行高 */
  color: #374151; /* 保持较深的文本颜色 */
  font-size: 16px; /* 增大字体 */
}

/* 新增的解答容器样式 */
.solution-text-container {
  background: #f0fdf4; /* 柔和的绿色背景 */
  padding: 20px;
  border-radius: 12px;
  border-left: 5px solid #22c55e; /* 绿色左边框 */
}

.solution-text {
  line-height: 1.8; /* 更大的行高，提升阅读舒适度 */
  font-size: 16px; /* 增大字体 */
  color: #1f2937; /* 使用更清晰的深色 */
}

/* 深度定制 Markdown 元素样式 */
.solution-text :deep(p),
.solution-text :deep(ol),
.solution-text :deep(ul) {
  margin-bottom: 1.2em;
}

.solution-text :deep(code) {
  background: #e5e7eb; /* 更明显的代码背景 */
  color: #111827;
  padding: 4px 8px;
  border-radius: 6px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 0.95em;
}

.solution-text :deep(pre) {
  background: #1f2937; /* 深色代码块背景 */
  color: #d1d5db;
  padding: 20px;
  border-radius: 8px;
  overflow-x: auto;
}

.solution-text :deep(blockquote) {
  border-left: 4px solid #a5b4fc; /* 引用块使用柔和的紫色 */
  padding-left: 16px;
  margin: 16px 0;
  color: #4b5563;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container { padding: 20px 16px; }
  .header-section { flex-direction: column; text-align: center; } /* 在小屏幕上恢复垂直布局 */
  .header-title-text { text-align: center; }
  .header-icon { margin-right: 0; margin-bottom: 16px; }
  .main-title { font-size: 36px; }
  .upload-content { padding: 24px; }
  .enhanced-uploader :deep(.el-upload) { padding: 40px 20px; }
  .upload-features { flex-direction: column; gap: 16px; }
  .results-grid { grid-template-columns: 1fr; }
  .loading-steps { flex-direction: column; gap: 12px; }
  .results-header { flex-direction: column; align-items: flex-start; gap: 16px; }
}
</style>